package com.marcowu.study.spb.tracing.resource;

import com.marcowu.study.spb.tracing.manager.SampleManager;
import com.marcowu.study.spb.tracing.zipkin.TraceUtil;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;

@Path("/tracing")
public class SampleResource {

  @Autowired
  private SampleManager sampleManager;

  private Tracer tracer = TraceUtil.getZipkinTracer("SampleResource");

  @GET
  @Path("helloworld")
  public String demo1(@Context HttpHeaders headers) {
    try (Scope scope = TraceUtil.startServerSpan(tracer, headers, "demo1")) {
      Span span = scope.span();
      span.setTag("demo1", "111");
      try {
        sampleManager.sayHello();
        sampleManager.bye();
      } catch (Exception e) {
        Tags.ERROR.set(scope.span(), true);
      } finally {
        span.finish();
      }
    }
    return "hello world";
  }

  @GET
  @Path("sayBye")
  public void sayBye(@Context HttpHeaders headers) {
    try (Scope scope = TraceUtil.startServerSpan(tracer, headers, "sayBye")) {
      Span span = scope.span();
      try {
        sampleManager.bye();
      } catch (Exception e) {
        Tags.ERROR.set(scope.span(), true);
      } finally {
        span.finish();
      }
    }
  }

  @GET
  @Path("sayHello")
  public void sayHello(@Context HttpHeaders headers) {
    try (Scope scope = TraceUtil.startServerSpan(tracer, headers, "sayHello")) {
      Span span = scope.span();
      try {
        sampleManager.hello();
      } catch (Exception e) {
        Tags.ERROR.set(scope.span(), true);
      } finally {
        span.finish();
      }
    }
  }

}
